package 对称二叉树;

/**
 * @author: zhengtao
 * @description: 另一棵树的子树
 * @version: 1.0
 * @date: 2022/10/29  17:06
 */
public class Demo572 {


    /**
     * Definition for a binary tree node.
     *
     * */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
          if(root==null){
              return false;
          }else if(root.val==subRoot.val){
              //根据子树遍历
              if(isSame(root,subRoot)){
                  return true;
              }else {
                  return isSubtree(root.left,subRoot)||isSubtree(root.right,subRoot);
              }
          }else {
                return isSubtree(root.left,subRoot)||isSubtree(root.right,subRoot);
          }
    }

    private boolean isSame(TreeNode root, TreeNode subRoot) {
        if(root==null&&subRoot==null){
            return true;
        }else if(root==null||subRoot==null||root.val!=subRoot.val){
            return false;
        }else {
            return  isSame(root.right,subRoot.right)&&isSame(root.left,subRoot.left);
        }
    }
}
